'''
Created on 16/03/2013

@author: Elfi
'''

class WebResource(object):
    '''
    classdocs
    '''
    
    def __init__(self):
        '''
        Constructor
        '''
        self.__timeElapsed = 0
        self.__status = ""
        self.__content_type = ""
        self.__headers = dict()
        self.__content_length = 0
        self.__url = ""
        self.__content = ""
        self.__internal_buf = ""
        self.__timestamp = ""

    def storeObject(self, connection):
        from re import match
        import StringIO
        import gzip
        
        if self.__headers.has_key("Content-Encoding") and "gzip" in self.__headers["Content-Encoding"].lower():
            '''Decompress content'''
            f = StringIO.StringIO( self.__internal_buf )
            zf = gzip.GzipFile(fileobj=f)
            buf = zf.read()
            zf.close()
        else:
            buf = self.__internal_buf
        
        self.__internal_buf = ""
        
        '''Encode according to the header information'''            
        m = match( r"(.+);.*charset=([\w|\-]+).*", self.contentType)           
        if (m is not None and "text" in m.group(1)) or 'text' in self.contentType:
            if m is not None and len(m.group(2)) > 0:
                self.__content = buf.decode(m.group(2))
            else:
                self.__content = buf.decode('utf8')
        
        '''Storing data only if there is content to store'''
        if len(self.__content) > 0:
            connection.storeObject(self)


    @property
    def timeElapsed(self):
        return self.__timeElapsed
    
    @timeElapsed.setter
    def timeElapsed(self,value):
        self.__timeElapsed = value
        
    @property
    def status(self):
        return self.__status
    
    @status.setter
    def status(self,value):
        self.__status = value
        
    @property
    def contentType(self):
        return self.__content_type
    
    @contentType.setter
    def contentType(self,value):
        self.__content_type = value 
        
    @property
    def contentLength(self):
        return self.__content_length
    
    @contentLength.setter
    def contentLength(self,value):
        self.__content_length = value
    
    @property
    def url(self):
        return self.__url
    
    @url.setter
    def url(self,value):
        self.__url = value
        
    @property
    def headers(self):
        return self.__headers
    
    def addHeader(self, key, value):
        self.__headers[key] = value
    
    def addContent(self, buf):
        self.__internal_buf += buf
        
    def docid(self):
        import time
        self.__timestamp = time.strftime("%Y%m%d_%H%M%S",time.gmtime())
	# Using only 64 bytes for the id
        return "__%s__%s" % (self.url[:64],self.__timestamp)
